package com.tzl.design_pattern.observer_pattern;

import java.util.ArrayList;
import java.util.List;

/**
 * 被观察者
 *
 * @author Zhilei Tang
 * @date Created in 2020/11/14 21:53
 */
public class WeatherData implements Subject {

  private final List<Observer> observers;

  private float temperature; // 温度
  private float humidity; // 湿度
  private float pressure; // 气压

  public void setMeasurements(float temperature, float humidity, float pressure) {
    this.temperature = temperature;
    this.humidity = humidity;
    this.pressure = pressure;
    // 气温信息发生变化时,通知所有观察者
    notifyObservers();
  }

  public WeatherData() {
    this.observers = new ArrayList<>();
  }

  @Override
  public void registerObserver(Observer observer) {
    observers.add(observer);
  }

  @Override
  public void removeObserver(Observer observer) {
    int i = observers.indexOf(observer);
    if (i >= 0) {
      observers.remove(i);
    }
  }

  @Override
  public void notifyObservers() {
    for (Observer observer : observers) {
      observer.update(temperature, humidity, pressure);
    }
  }
}
